package com.ala4.oxcafe.boot.manager;

import com.ala4.oxcafe.properties.SecurityProperties;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.AuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import java.util.function.Supplier;

/**
 * 鉴权管理器-API鉴权
 *
 * @author PING
 * @version 1.0
 * @date 2024/12/25 14:29
 */
@Slf4j
@Component
public class APIAuthorizationManager<RequestAuthorizationContext> implements AuthorizationManager<org.springframework.security.web.access.intercept.RequestAuthorizationContext> {

    private final SecurityProperties securityProperties;

    public APIAuthorizationManager(SecurityProperties securityProperties) {
        this.securityProperties = securityProperties;
    }

    @Override
    public AuthorizationDecision check(Supplier<Authentication> authentication, org.springframework.security.web.access.intercept.RequestAuthorizationContext object) {

        // 如果是匿名token 直接拒绝 不在这里管理
        if (authentication.get() instanceof AnonymousAuthenticationToken) {
            return new AuthorizationDecision(false);
        }

        if (Boolean.FALSE.equals(securityProperties.getApiUrlAuthentication())) {
            return new AuthorizationDecision(true);
        }

        HttpServletRequest request = object.getRequest();
        String path = request.getRequestURI();
        // 忽略对 /error 路径的权限检查
        if ("/error".equals(path)) {
            return new AuthorizationDecision(true);
        }
        log.info("用户请求URL:{}", path);
        // TODO 鉴权逻辑
        log.info("URL鉴权逻辑:{}", authentication.get());
        log.info("{}", object);
        return new AuthorizationDecision(false);
    }
}
